package com.example.recycleviewdemo;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class FriendAdapter extends RecyclerView.Adapter<FriendAdapter.ViewHolder> {
    private List<Friend> mFriendList;  //数据源，在new此类的时候传入

    //FriendAdapter的构造方法，加入了数据源参数，在构造的时候赋值给mFriendList
    public FriendAdapter(List<Friend> FriendList) {
        mFriendList = FriendList;
    }

    //用于创建ViewHolder实例,并把加载的布局传入到ViewHolder的构造函数去
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        holder.headImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                Friend friend = mFriendList.get(position);
                Toast.makeText(view.getContext(), "你要跟" + friend.getFriendName() + "聊天", Toast.LENGTH_LONG).show();
            }
        });
        return holder;
    }

    //是用于对子项的数据进行赋值,会在每个子项被滚动到屏幕内时执行。position得到当前项的Friend实例
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        Friend Friend = mFriendList.get(position);
        holder.headImage.setImageResource(Friend.getHeadImageId());
        holder.txtName.setText(Friend.getFriendName());
    }

    //返回RecyclerView的子项数目
    @Override
    public int getItemCount() {
        return mFriendList.size();
    }

    //静态内部类， 每个条目对应的布局
    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView headImage;
        TextView txtName;

        public ViewHolder(View view) {
            super(view);
            headImage = (ImageView) view.findViewById(R.id.head_image);
            txtName = (TextView) view.findViewById(R.id.name);
        }

    }
}
